<?php
namespace app\controller;

use support\Request;
use support\Redis;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http;

class ChatController
{
    // 存储所有连接的客户端
    protected static $clients = [];

    public function connect(Request $request)
    {
        $connection = $request->connection;
        $clientId = uniqid();
        self::$clients[$clientId] = $connection;
        $connection->clientId = $clientId;
        // 向客户端发送连接成功消息
        $connection->send(json_encode(['type' => 'connect', 'message' => '连接成功', 'clientId' => $clientId]));

        return response('200');
    }

    public function message(Request $request)
    {
        $connection = $request->connection;
        $data = json_decode($request->rawBody(), true);
        $message = $data['message'];
        $senderId = $connection->clientId;

        // 广播消息给所有客户端
        foreach (self::$clients as $clientId => $clientConnection) {
            if ($clientId != $senderId) {
                $clientConnection->send(json_encode(['type' => 'message', 'senderId' => $senderId, 'message' => $message]));
            }
        }

        return response('');
    }

    public function disconnect(Request $request)
    {
        $connection = $request->connection;
        $clientId = $connection->clientId;
        if (isset(self::$clients[$clientId])) {
            unset(self::$clients[$clientId]);
        }
        return response('');
    }
}